<template>
  <div>
    <a-row :gutter="20">
      <a-col :span="14">
        <!-- 仪器串组合推荐 -->
        <a-spin :spinning="spinning">
          <a-table :pagination="false" :columns="combinationColumns" :data-source="combSuggestData">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.title === '仪器串组合'">
                {{ record.instrumentNameList.toString().replace(/,/g, " + ") }}
              </template>
              <template v-if="column.dataIndex === 'operation'">
                <a-button @click="updateCombSuggest(record)">修改 </a-button>
                <!-- <a-button style="margin-left: 10px" @click="delCombSuggest(record.id)">删除 </a-button> -->
              </template>
            </template>
          </a-table>
          <a-table :pagination="false" :showHeader="false" :columns="instrumentListColumns" :data-source="instrumentList">
            <!-- <template #title>{{ instrumentTableTitle }}</template> -->
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'operation'">
                <a-popconfirm title="请选择在下方或在上方插入" ok-text="向下" cancel-text="向上"
                  @confirm="insertToDown(record.instrumentId)" @cancel="insertToUp(record.instrumentId)">
                  <a-button style="margin-left: 30px">插入 </a-button>
                </a-popconfirm>
                <a-button style="margin-left: 10px" @click="delInstrument(record.instrumentId)"> 删除 </a-button>
              </template>
            </template>
          </a-table>
          <a-row>
            <a-button type="dashed" style="width: 100%" @click="saveCombSuggest">
              <template #icon><node-index-outlined /></template>保存
            </a-button>
          </a-row>
        </a-spin>
      </a-col>
      <a-col :span="10">
        <a-spin :spinning="spinning">
          <div ref="d3CanvasRef">
            <canvasIns :data="instrumentList"></canvasIns>
          </div>
        </a-spin>
      </a-col>
    </a-row>
  </div>
  <!-- 选择仪器弹窗 -->
  <AntdConfirmModal @confirm="submitUpdateForm" :title="modalTitle" ref="instrumentModalRef" width="1200px">
    <a-row style="margin-bottom: 10px">
      <a-select ref="select" v-model:value="optionType" style="width: 120px">
        <a-select-option value="instrument">仪器信息</a-select-option>
        <a-select-option value="horsehead">马笼头</a-select-option>
      </a-select></a-row>
    <horsehead-popup v-if="optionType === 'horsehead'" @horseheadSelection="horseheadSelection"></horsehead-popup>
    <instrument-popup v-if="optionType === 'instrument'" @instrumentSelection="instrumentSelection"></instrument-popup>
  </AntdConfirmModal>
</template>
<script setup>
import canvasIns from "@/custom/preTest/pages/plan/components/instrument/canvas.vue";
import html2canvas from "html2canvas";
import InstrumentPopup from '@/custom/preTest/pages/plan/components/instrument/type/InstrumentPopup.vue'
import HorseheadPopup from "@/custom/preTest/pages/plan/components/instrument/type/HorseheadPopup.vue";
import { NodeIndexOutlined } from "@ant-design/icons-vue";
import { cloneDeep } from "lodash-es";
import WellInstrument from "@/api/tool/instrument.js";
import WellHorsehead from "@/api/tool/horsehead.js";
import WellCombination from "@/api/tool/combination.js";
import useApp from "@/hooks";
const { $, proxy } = useApp();
const props = defineProps({
  combinationId: {
    type: String,
  }
});
const emit = defineEmits(["getCombination"]);
const spinning = ref(false);
const d3CanvasRef = ref(null);
const modalTitle = ref(null);
const instrumentId = ref(null);
const instrumentModalRef = ref(null);
const instrumentSelectionData = ref([])
const horseheadSelectionData = ref([])
const combinationId = ref(null)
// const instrumentTableTitle = ref(null);
// const numberOfPasses = ref(1);
const formState = ref({
  combinationName: "",
  combinationSeries: "CPlog",
  instrumentIdList: [],
})
const instrumentList = ref([]);
const combSuggestData = ref([]);
//仪器串组合推荐表内容
const combinationColumns = ref([
  // {
  //   dataIndex: "numbers",
  //   title: "趟次",
  //   width: 80,
  // },
  {
    title: "仪器串组合",
    dataIndex: "instrumentNameList",
    key: "instrumentNameList",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
    width: 200,
  },
]);
const instrumentListColumns = ref([
  {
    dataIndex: "instrumentId",
    width: 100,
  },
  {
    dataIndex: "instrumentName",
  },
  {
    dataIndex: "operation",
    fixed: "right",
    width: 230,
  },
]);
const optionType = ref("instrument")
//仪器串推荐列表负载内容
const combSuggestListQuery = ref({
  schemeId: localStorage.getItem("schemeId"),
  order: "ASC",
  pageNum: 1,
  pageSize: 100,
  searchKey: undefined,
  sortBy: "numbers",
});
//仪器串推荐更新/新建负载内容
const combSuggesQuery = ref({});

//删除仪器串组合推荐
// const delCombSuggest = (key) => {
//   spinning.value = true;
//   deleteOne(key).then((res) => {
//     instrumentList.value = [];
//     // instrumentTableTitle.value = undefined;
//     $.showToast({
//       title: "删除成功",
//       icon: "success",
//     });
//     spinning.value = false;
//     getCombSuggestDataList();
//   }).catch((err) => {
//     spinning.value = false;
//   });
// };
//更新仪器串组合推荐插入仪器
const insertToDown = (id) => {
  modalTitle.value = "选择向下插入的仪器";
  instrumentId.value = id;
  instrumentModalRef.value.openModal();
};
const insertToUp = (id) => {
  modalTitle.value = "选择向上插入的仪器";
  instrumentId.value = id;
  instrumentModalRef.value.openModal();
};
//更新仪器串组合推荐（修改按钮）
const updateCombSuggest = (record) => {
  spinning.value = true;
  combSuggesQuery.value = record;
  console.log(record);
  // instrumentTableTitle.value = `第 ${record.numbers} 趟仪器串组合推荐`;
  const horseIndex = record.instrumentNameList.findIndex((element) => element.includes("马笼头"));
  const allInstrumentIdList = JSON.parse(JSON.stringify(record.instrumentIdList));
  const horseIdList = allInstrumentIdList.splice(horseIndex, 1);
  const instrumentContentList = [];
  const horseList = [];
  const promises = allInstrumentIdList.map((id) => WellInstrument.queryOne(id));
  Promise.all(promises).then((results) => {
    // results 数组包含了按照请求顺序返回的数据
    results.forEach((res) => {
      instrumentContentList.push(res);
    });
  });
  horseIdList.forEach((id) => {
    WellHorsehead.getOne(id).then((res) => {
      res.instrumentId = res.horseheadId;
      res.outerDiameter = res.maxDiameter;
      res.instrumentName = res.horseheadName;
      res.weight = 0;
      horseList.push(res);
    });
  });
  setTimeout(() => {
    instrumentList.value = [...horseList, ...instrumentContentList];
    spinning.value = false;
  }, 300);
};

//删除仪器
function delInstrument(id) {
  instrumentList.value = instrumentList.value.filter(item => item.instrumentId !== id);
}

//仪器弹窗
function instrumentSelection(e) {
  instrumentSelectionData.value = e
}
//马笼头弹窗
function horseheadSelection(e) {
  horseheadSelectionData.value = e
}
// 选择仪器/马笼头
function submitUpdateForm() {
  horseheadSelectionData.value.forEach(e => {
    e.instrumentId = e.horseheadId
    e.instrumentName = e.horseheadName
  })
  let array = [...horseheadSelectionData.value, ...instrumentSelectionData.value]
  console.log('array', array);
  if (modalTitle.value === '选择添加的仪器') {
    instrumentList.value = [...instrumentList.value, ...array]
  }
  else {
    let index = instrumentList.value.findIndex(item => item.instrumentId == instrumentId.value)
    const position = modalTitle.value === '选择向上插入的仪器' ? 0 : 1
    instrumentList.value.splice(index + position, 0, ...array);
    instrumentList.value = [...instrumentList.value]
    instrumentId.value = null
  }
  console.log('instrumentList.value', instrumentList.value);
  horseheadSelectionData.value = []
  instrumentSelectionData.value = []
  instrumentModalRef.value.closeModal()
}
//保存
function saveCombSuggest() {
  spinning.value = true;
  if (instrumentList.value.length != 0) {
    instrumentList.value.forEach(res => {
      formState.value.instrumentIdList.push(res.id)
    })
    setTimeout(() => {
      html2canvas(d3CanvasRef.value).then((canvas) => {
        const imageData = canvas.toDataURL("image/png");
        formState.value.file = imageData;
        formState.value.combinationName = '非常规';
        console.log('formState.value', formState.value);
        WellCombination.createOne(formState.value).then(res => {
          // console.log('create', res);
          $.showToast({
            title: '新增成功',
            icon: 'success'
          })
          combinationId.value = res.id
          emit("getCombination", res.id);
          getCombSuggestDataList(combinationId.value)
          instrumentList.value = []
          combSuggestData.value = []
          formState.value = {}
        })
      });
      spinning.value = false;
    }, 1000);
  } else {
    $.showToast({ title: '提交成功', icon: 'success' })
    emit("getCombination", combinationId.value);
  }
}
//获取已选择的仪器串推荐数据
function getCombSuggestDataList(e) {
  let id
  if (e) { id = e }
  else { id = props.combinationId }
  WellCombination.queryOne(id).then((res) => {
    console.log('get', res);
    combinationId.value = res.id
    formState.value.combinationSeries = res.combinationSeries
    combSuggestData.value.push(res);
    // console.log(combSuggestData.value);
  });
}
getCombSuggestDataList();
</script>
